# 
# Copyright (C) 2013 hakan.johansson@gmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################
import Cookie, datetime, time, random, pickle, sys
from log import *
from config import *

class _CookieHandler:
    def __init__(self):
        pass
        
    def createCookie(self):
        cookie = Cookie.SimpleCookie()
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=1) 
        
        cookie = Cookie.SimpleCookie()
        sessionId = random.randint(1, 1000000000)
        cookie["session"] = sessionId
        cookie["session"]["domain"] = domain
        cookie["session"]["secure"] = secureCookie
        cookie["session"]["path"] = cookiePath
        cookie["session"]["expires"] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
        self._addSessionToFile(sessionId, cookie["session"]["expires"])
        
        Log.printToFile("CookieHandler::createCookie() experation time: %s"%cookie["session"]["expires"])
        return cookie

    def deleteCookie(self, sessionId):
        cookie = Cookie.SimpleCookie()
        expiration = datetime.datetime.now() + datetime.timedelta(days=-1)
        cookie = Cookie.SimpleCookie()
        cookie["session"] = sessionId
        cookie["session"]["domain"] = domain
        cookie["session"]["path"] = cookiePath
        cookie["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")

        self._cleanupSessionsFile()

        return cookie

    def getSessionId(self, environ):
        Log.printToFile("CookieHandler::getSessionId()");
        cookie = Cookie.SimpleCookie(environ.get("HTTP_COOKIE",""))
        sessionId = -1
        if cookie.has_key("session"):
            sessionId = self._getSessionFromFile(cookie["session"].value)
        return sessionId

    sessionId = property(getSessionId)


    def _cleanupSessionsFile(self):
        Log.printToFile("CookieHandler::_cleanupSessionsFile()")
        sessions = self._getSessions()
        #remove expired cookies
        for sessionId in sessions.keys():
            expires = sessions[sessionId]
            cookieExpireDate = datetime.datetime.strptime(expires, "%a, %d %b %Y %H:%M:%S")
            #Log.printToFile("CookieHandler::_cleanupSessionsFile() sessionId: %s cookie:now  %s < %s"%(sessionId, str(cookieExpireDate), str(datetime.datetime.utcnow())))
            if cookieExpireDate < datetime.datetime.utcnow():
                #Log.printToFile("CookieHandler::_cleanupSessionsFile() removing expired cookie: %s"%(sessionId))
                del sessions[sessionId]

        self._saveSessions(sessions)

    def _addSessionToFile(self, sessionId, expires):
        Log.printToFile("CookieHandler::_addSessionToFile() sessionId: %s expires: %s"%(sessionId, expires));
        sessions = self._getSessions()
        expires = expires.replace("GMT", "")
        expires = expires.strip()
        sessions[str(sessionId)] = expires
        self._saveSessions(sessions)

    def _getSessionFromFile(self, sessionId):
        Log.printToFile("CookieHandler::_getSessionFromFile()) sessionID:%s"%(sessionId))
        sessions = self._getSessions()
        if sessionId in sessions.keys():
            expires = sessions[sessionId]
            cookieExpireDate = datetime.datetime.strptime(expires, "%a, %d %b %Y %H:%M:%S")
            #Log.printToFile("CookieHandler::_getSessionFromFile()) expires:%s"%(str(cookieExpireDate)))
            if cookieExpireDate > datetime.datetime.utcnow():
                return sessionId
            else:
                Log.printToFile("CookieHandler::_getSessionFromFile()) Error: cookie has expired!")
                return -1
        else:
            Log.printToFile("CookieHandler::_getSessionsFromFile: Error session was not found!!")
            return -1

    def _saveSessions(self, sessions):
        Log.printToFile("CookieHandler::_saveSessions()")
        try:
            pickle.dump(sessions, (open(sessionsFile, "wb")))
        except:
            Log.printToFile("CookieHandler::_saveSessions: failed to save sessions!(%s)"%(sys.exc_info()[0]))
            
    def _getSessions(self):
        Log.printToFile("CookieHandler::_getSessions()")
        try:
            sessions = pickle.load(open(sessionsFile, "rb"))
        except:
            Log.printToFile("CookieHandler::_getSessions: failed to get sessions! (%s)"%(sys.exc_info()[0]))
            sessions = {}

        #Log.printToFile("CookieHandler::_getSessions() sessions:\n%s"%str(sessions))
        return sessions
        
_cookieHandler = _CookieHandler()

def CookieHandler():
    return _cookieHandler

